package com.ukao.cashregister.ui.splash;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.WifiTableAdapter;
import com.ukao.cashregister.base.BaseFragment;
import com.ukao.cashregister.bean.ComparatorComment;
import com.ukao.cashregister.bean.SearchHistorysBean;
import com.ukao.cashregister.db.SearchHistorysDao;
import com.ukao.cashregister.dialog.WifiPassDialogFragment;
import com.ukao.cashregister.dialog.WifiStrongDialogFragment;
import com.ukao.cashregister.eventbus.WifiEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.ui.login.WifiActivity;
import com.ukao.cashregister.utils.AppManager;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.ThreadUtils;
import com.ukao.cashregister.utils.WifiAdminUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class SplashWifiFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    Unbinder unbinder;
    @BindView(R.id.next_step)
    TextView nextStep;
    @BindView(R.id.back_btn)
    TextView backBtn;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ArrayList<ScanResult> mlist;
    private WifiTableAdapter mWifiTableAdapter;
    private WifiAdminUtils mWifiAdmin;
    private WifiReceiver mReceiver;
    private SearchHistorysDao dao;
    private ArrayList<SearchHistorysBean> save;
    private boolean isloginEnter;


    public static SplashWifiFragment newInstance(boolean isloginEnter, String param2) {
        SplashWifiFragment fragment = new SplashWifiFragment();
        Bundle args = new Bundle();
        args.putBoolean(ARG_PARAM1, isloginEnter);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isloginEnter = getArguments().getBoolean(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_splash_wifi, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        registerReceiver();
        mWifiAdmin.startScan();

    }


    @Override
    protected void initListener() {
        super.initListener();
        mWifiTableAdapter.setOnItemClickListener(mOnItemClickListener);

    }

    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            ScanResult scanResult = (ScanResult) o;
            isConnect(scanResult);


        }
    };

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (!CheckUtils.isNull(mReceiver))
        _mActivity.unregisterReceiver(mReceiver);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        dao = new SearchHistorysDao(_mActivity);
        mlist = new ArrayList<ScanResult>();
        initLinearRecyclerView(recyclerView);
        mWifiTableAdapter = new WifiTableAdapter(_mActivity, mlist, true);
        recyclerView.setAdapter(mWifiTableAdapter);
        mWifiAdmin = new WifiAdminUtils(_mActivity);
        if (isloginEnter) {
            backBtn.setVisibility(View.VISIBLE);
            nextStep.setVisibility(View.GONE);



        }



    }




    /**
     * 连接wifi对话框
     */
    private void isConnect(final ScanResult scanResult) {
        if (mWifiAdmin.isConnect(scanResult)) {
            // 已连接，显示连接状态对话框
            WifiStrongDialogFragment mWifiStrongDialogFragment = new WifiStrongDialogFragment();
            Bundle mBundle = new Bundle();
            mBundle.putParcelable(ARG_PARAM1, scanResult);
            mWifiStrongDialogFragment.setArguments(mBundle);
            mWifiStrongDialogFragment.show(getChildFragmentManager(),mWifiStrongDialogFragment.getClass().getName());

        } else {
            if (!mWifiAdmin.checkIsCurrentWifiHasPassword(scanResult.capabilities)) {
                ThreadUtils.runOnBackgroundThread(new Runnable() {
                    @Override
                    public void run() {
                        boolean iswifi = mWifiAdmin.addNetwork(mWifiAdmin.createWifiInfo(scanResult.SSID, "",0));//连接wifi
                    }
                });


            } else {
                // 未连接显示连接输入对话框
                WifiPassDialogFragment mWifiPassDialogFragment = new WifiPassDialogFragment();
                Bundle mBundle = new Bundle();
                mBundle.putParcelable(ARG_PARAM1, scanResult);
                mWifiPassDialogFragment.setArguments(mBundle);
                mWifiPassDialogFragment.setOnSureClickListener(mOnDialogSureClickListener);
                mWifiPassDialogFragment.show(getChildFragmentManager(),mWifiPassDialogFragment.getClass().getName());
            }


        }
    }
    private OnDialogSureClickListener mOnDialogSureClickListener=new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            Map mMap = (Map) message;
            final      String    txtWifiNames= (String) mMap.get(ARG_PARAM1);
            final   String    wifiPass= (String) mMap.get(ARG_PARAM2);
            final   int    type= (int) mMap.get(ARG_PARAM3);
            ThreadUtils.runOnBackgroundThread(new Runnable() {
                @Override
                public void run() {
                    mWifiAdmin.addNetwork(mWifiAdmin.createWifiInfo(txtWifiNames,wifiPass,type));//连接wifi

                }
            });

        }
    };

    private void registerReceiver() {
        mReceiver = new WifiReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        _mActivity.registerReceiver(mReceiver, filter);
    }

    @OnClick({R.id.next_step, R.id.back_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.next_step:
                save = dao.findAll();
                if (!CheckUtils.isEmpty(save)) {
                    start(ClauseFragment.newInstance("", ""));
                } else {
                    start(SerialumberFragment.newInstance("", ""));
                }

                break;
            case R.id.back_btn:
                AppManager.getAppManager().finishActivity(WifiActivity.class);
                break;

        }
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(WifiEvent event) {
        switch (event.getMessage()) {
//            case  link:/*链接wifi*/
//
//                Map mMap = (Map) event.getData();
//                String    txtWifiNames= (String) mMap.get(ARG_PARAM1);
//                String    wifiPass= (String) mMap.get(ARG_PARAM2);
//                int    type= (int) mMap.get(ARG_PARAM3);
//                mWifiAdmin.addNetwork(mWifiAdmin.createWifiInfo(txtWifiNames,wifiPass,type));//连接wifi
//
//                break;
            case  notSave:

                mWifiAdmin.disConnectionWifi(mWifiAdmin.getConnNetId());

                break;
        }
    }



    private class WifiReceiver extends BroadcastReceiver {
        protected static final String TAG = "ukao";


        @Override
        public void onReceive(Context context, Intent intent) {

            List<ScanResult> wifiList = mWifiAdmin.getWifiManager().getScanResults();
            setWifiData(wifiList);
            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {// wifi连接上与否
                Log.d(TAG, "网络已经改变");

                NetworkInfo info = intent
                        .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    Log.d(TAG, "wifi已经断开");
                    setTextcolor("wifi已经断开", false);

                } else if (info.getState().equals(NetworkInfo.State.CONNECTING)) {
                    Log.d(TAG, "正在连接...");
                    setTextcolor("正在连接...", false);
                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    WifiManager wifiManager = (WifiManager) context
                            .getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    Log.d(TAG, "：连接到网络" + wifiInfo.getBSSID());
                    setTextcolor("已连接到网络，下一步", true);
                }

            } else if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR,
                        0);

                switch (error) {

                    case WifiManager.ERROR_AUTHENTICATING:
                        T.show("链接失败");
                        Log.d(TAG, "密码认证错误Code为：" + error);
                        setTextcolor("连接到网络", false);
                        break;

                    default:
                        break;
                }
            } else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                ;
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                Log.e("ukao", "wifiState" + wifiState);

                switch (wifiState) {

                    case WifiManager.WIFI_STATE_DISABLING:/*Wifi关闭*/

                        break;
                    case WifiManager.WIFI_STATE_DISABLED:/*Wifi关闭完*/
                        setTextcolor("Wifi未打开", false);

                        break;
                    case WifiManager.WIFI_STATE_ENABLING:/*Wifi打开*/

                        break;
                    case WifiManager.WIFI_STATE_ENABLED:/*Wifi完*/


                        break;

                }
            }
        }

    }


    private void setTextcolor(String msg, boolean enabled) {
        nextStep.setText(msg);
        nextStep.setEnabled(enabled);
    }


    private void setWifiData(List<ScanResult> tmpList) {

        if (CheckUtils.isEmpty(tmpList)) {
            mWifiTableAdapter.getDatas().clear();
            mWifiTableAdapter.notifyDataSetChanged();
        } else {
            Collections.sort(tmpList,new ComparatorComment());
            mWifiTableAdapter.setDatas(tmpList);

        }


    }



}






